package cn.doitedu.basic.jdk.juc;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * CompleteFuture 是对Future的增强，能在Future的基础上对结果进行一些回调类的工作
 */
public class CompleteFutureDemo {


    private static ExecutorService cachePool = Executors.newCachedThreadPool();

    public static void main(String[] args) throws Exception{
        CompletableFuture<String> completableFutureOne = new CompletableFuture<>();

        cachePool.execute(()->{
            try {
                Thread.sleep(3000);
                //这里执行完成后，会立即回调whenComplete（如果有些的话）
                completableFutureOne.complete("异步任务执行结果");
                Thread.sleep(2000);
                System.out.println(Thread.currentThread().getName());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });



        // WhenComplete 方法返回的 CompletableFuture 仍然是原来的 CompletableFuture 计算结果.
        CompletableFuture<String> completableFutureTwo = completableFutureOne.whenComplete((s, throwable) -> {
            System.out.println("当异步任务执行完毕时打印异步任务的执行结果:" + s);
        });

        CompletableFuture<Integer> completableFutureThree = completableFutureOne.thenApply(s -> {
            System.out.println("当异步任务执行结束时, 根据上一次的异步任务结果, 继续开始一个新的异步任务!");

            System.out.println("---->" + s);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            return s.length();

        });


        System.out.println("阻塞方式获取执行结果:" + completableFutureThree.get());
        cachePool.shutdown();


    }

}
